#include "preprocessing.hpp"
#include <fstream>  

#include <allheaders.h> // leptonica main header for image io
#include <baseapi.h> // tesseract main header


using namespace cv;
using namespace std;

int main(int argc, char *argv[])
{
       if (argc <3)
         {
         	cout<<"Usage: OCR input_image outName showProcess"<<endl;
         	return 1;
         }
         Mat src = imread(argv[1]);
         char * outName=argv[2];
         int showProcess;
         if(argc==4)
            showProcess=atoi(argv[3]);
        else
        	showProcess=0;
         ofstream out;
         out.open(outName);  
         if(src.empty()) 
          {
             cout<<"can't read image"<<endl;
             return 1;
          }
            src=Mat(src,Rect(0,int(0.36*src.rows),src.cols, int(0.36*src.rows)));      
          resize(src,src,Size(700,int(700*src.rows/src.cols)),0,0,CV_INTER_CUBIC);
         
          std::vector<Rect> boxes;
          boxes=getCandidateBox(src);
          if(showProcess)
          {
              namedWindow( "ori", CV_WINDOW_AUTOSIZE );
              namedWindow( "bin", CV_WINDOW_AUTOSIZE );
              imshow("ori",src);
              cout<<src.cols<<"   "<<src.rows<<endl;
              waitKey(0);
          }
          tesseract::TessBaseAPI tess;
          tesserInit(tess);

          sortRect(boxes);
          for(int i=0; i<boxes.size();i++)
          {
          	//cout<<"x: "<<boxes[i].tl().x<<"y: "<<boxes[i].tl().y<<endl;
          	Mat ori=Mat ( src , boxes[i] );
          	if(showProcess)
          	{
          	    imshow("bin",ori);
          	    waitKey(0);
          	}
               boxImageProcessing(ori);
               if(showProcess)
               {	   
          	    imshow("bin",ori);
          	    waitKey(0);
              }
               
          	tess.SetImage((uchar*)ori.data, ori.size().width, ori.size().height, ori.channels(), ori.step1());
	tess.Recognize(0);
	const char* text = tess.GetUTF8Text();
	if(showProcess)
		cout<<text<<endl;
	out<<text<<endl;
          }
             out.close();
             system("rm -r zzyyww*");
          return 0;
}